import { NextResponse } from "next/server";
import prisma from '@/lib/prisma';
import { getUser } from "@/lib/authUtils";
const tencentcloud = require("tencentcloud-sdk-nodejs-asr");

const AsrClient = tencentcloud.asr.v20190614.Client;

// 初始化客户端配置
const clientConfig = {
  credential: {
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
  },
  region: "ap-shanghai",
  profile: {
    httpProfile: {
      endpoint: "asr.tencentcloudapi.com",
    },
  },
};

const client = new AsrClient(clientConfig);
// 创建识别任务并上传文件到OSS
export async function POST(request: Request): Promise<Response> {
  const userid = await getUser(request);
  if (!userid) {
    return NextResponse.json(
      { error: '未授权或登录信息过期，请登录' },
      { status: 401 }
    );
  }
  if (userid instanceof NextResponse) {
    return userid;
  }

  try {
    const { fileUrl, filekey } = await request.json();
    if (!fileUrl) {
      return NextResponse.json(
        { error: "fileUrl is required" },
        { status: 400 }
      );
    }

    // 创建语音识别任务
    const params = {
      EngineModelType: "16k_zh", // 16k中文通用模型
      ChannelNum: 1, // 单声道
      ResTextFormat: 2, // 返回字幕格式
      SourceType: 0, // 音频URL
      Url: fileUrl,
      SpeakerDiarization: 1, // 开启说话人分离
      FilterDirty: 1, // 过滤脏词
      FilterModal: 1, // 过滤语气词
      ConvertNumMode: 1, // 数字转换
    };

    const data = await client.CreateRecTask(params);
    
    if (!data?.Data?.TaskId) {
      throw new Error("Invalid response data from CreateRecTask");
    }

    // 创建新的vms_asr记录
    const newSubtitle = await prisma.vms_asr.create({
      data: {
        id: crypto.randomUUID(),
        task_id: BigInt(data.Data.TaskId),
        status: "0", // 0表示处理中
        filekey: filekey,
        create_time: new Date(),
        userid: userid,
        subtitle_text: '',
      },
    });
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        subtitle_count: {
          increment: 1
        }
      }
    })

    // 将BigInt转换为字符串以避免序列化问题
    const serializedSubtitle = {
      ...newSubtitle,
      id: newSubtitle.id.toString(),
      task_id: newSubtitle.task_id?.toString()
    };

    return NextResponse.json(serializedSubtitle);
    
  } catch (error) {
    console.error("Error creating recognition task:", error);
    return NextResponse.json(
      { error: "Failed to create recognition task" },
      { status: 500 }
    );
  }
}
